package com.qjdchina.sku.front.web.util;


import java.io.File;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片上传
 * @author shenpingfeng
 * 2016年5月28日
 */
public class ImageUtil {
    private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    private static String savePath = "/srv/upload/sku/"; //文件保存路径


    /**
     * 保存图片文件
     *
     * @param fileData
     * @return
     * @throws Exception
     */
    public static String saveImage(byte[] fileData) throws Exception {
        String hashedName = DigestUtils.md5Hex(fileData);
        String basePath = "/" + hashedName.substring(0, 2) + "/" + hashedName.substring(2, 4);
        FileUtils.forceMkdir(new File(savePath + basePath));
        String relativePath = basePath + File.separator + hashedName + ".gif";

        String picSavePath = savePath + File.separator + relativePath;

        logger.info("picSavePath = " + picSavePath);
        File saveFile = new File(picSavePath);
        FileUtils.writeByteArrayToFile(saveFile, fileData);

        return  relativePath;
    }

    public static String saveImage(MultipartFile pic) throws Exception {
        if (!validateFileType(pic)) {
            throw new RuntimeException("上传文件类型错误！");
        }
        return saveImage(pic.getBytes());
    }

    private static boolean validateFileType(MultipartFile file) {
        if (file != null && file.getSize() > 0) {
            List<String> allowType = Arrays.asList("image/jpg", "image/jpeg", "image/png", "image/gif");
            return allowType.contains(file.getContentType().toLowerCase());
        }
        return false;
    }

}
